package com.heima.wemedia.task;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

@Slf4j
//@Component
public class MyTask {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Scheduled(cron = " */5 * * * * ?")
    public void task(){

        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //        创建锁对象,并没有访问redis
                RLock rLock = redissonClient.getLock("myLock");
//          去尝试获取锁
                boolean b = rLock.tryLock();
                if(b){
                    try {
//        做业务
                        log.info("1==获取到锁，执行业务");
                        Thread.sleep(4000);

                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        if(b) {
//            释放锁
                            rLock.unlock();
                            log.error("1===释放锁");
                        }
                    }
                }else{
                    log.error("1===没有获得锁，结束");
                }
            }
        });

        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //        创建锁对象,并没有访问redis
                RLock rLock1 = redissonClient.getLock("myLock");
                //          去尝试获取锁
                boolean b1 = rLock1.tryLock();
                if (b1) {
                    try {
//        做业务
                        log.info("2==获取到锁，执行业务");
                        Thread.sleep(4000);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (b1) {
//            释放锁
                            rLock1.unlock();
                            log.error("2===释放锁");
                        }
                    }
                } else {
                    log.error("2==没有获得锁，结束");
                }
            }
        });






    }
}
